﻿using Microsoft.OpenApi.Models;
using System.Reflection;
using Zwt.System.Common.Helpers;
using Zwt.System.Host.Authorization;

namespace Zwt.System.Host.Extensions.Setup
{
    public static class SetupSwagger
    {
        public static void AddSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddSwaggerGen(c =>
            {

                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1.0",
                    Title = $"{AppSettings.Configuration["Startup:ApiName"]} 接口文档",
                    Description = $"{AppSettings.Configuration["Startup:ApiName"]} HTTP API "
                });

                try
                {
                    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename),true);//默认的第二个参数是false，这个是controller的注释，记得修改
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Xml 文件丢失，请检查并拷贝。\n{ex.Message}");
                }

                // 开启加权小锁
                // 是一种自定义过滤器，可以用来添加自定义标记、修改操作描述或添加其他操作元数据
                c.OperationFilter<AppendAuthorizeFilter>();

            });

        }

        public static void UseSwaggerSetup(this IApplicationBuilder app)
        {
            app.UseSwagger();
            app.UseSwaggerUI();
            //app.UseSwaggerUI(c =>
            //{
            //    var ApiName = AppSettings.Configuration["Startup:ApiName"];

            //    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
            //    c.RoutePrefix = string.Empty;
            //});
        }
    }
}
